package com.lxf.cloudotherserve.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lxf.cloudfeign.client.userClient.UserClient;
import com.lxf.cloudotherserve.bean.PlayHistoryBean;
import com.lxf.cloudotherserve.bean.UserCLRBean;
import com.lxf.cloudotherserve.bean.UserCommentBean;
import com.lxf.cloudotherserve.mapper.PlayHistoryItemRepository;
import com.lxf.cloudotherserve.mapper.PlayHistoryMapper;
import com.lxf.cloudotherserve.mapper.UserCLRItemRepository;
import com.lxf.cloudotherserve.mapper.UserCommentItemRepository;
import com.lxf.cloudotherserve.service.PlayHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 罗兴发
 * @data 2025/6/27 17:47
 * @description：浏览记录-业务实现层
 */
@Slf4j
@Service
public class PlayHistoryServiceImpl implements PlayHistoryService {

    @Resource
    PlayHistoryMapper playHistoryMapper;

    @Resource
    private PlayHistoryItemRepository playHistoryItemRepository;

    @Resource
    private UserCLRItemRepository userCLRItemRepository;

    @Resource
    private UserCommentItemRepository userCommentItemRepository;

    @Resource
    private UserClient userClient;


    /**
     * 供其他服务调用
     * @param json
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addPlayHistory(JSONObject json,HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);

        Integer userId = null;
        if (null!=o) {
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex + 1);
            userId = Integer.valueOf(userIdSub);//用户ID
        }
        //传递的参数
        String objId = json.getString("obj_id");//对象ID，如：商品编码
        Integer type = json.getInteger("obj_type");//对象类型：0商品 其他待定
        String content = json.getString("title");//标题
        String cover = json.getString("cover");//封面

        //时间规格化
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());

        //添加浏览记录
        PlayHistoryBean ph = new PlayHistoryBean();
        ph.setPhType(type);
        ph.setUserId(userId);
        ph.setObjId(objId);
        ph.setObjTitle(content);
        ph.setObjImage(cover);
        ph.setAddTime(addTime);

        //list封装
        List<PlayHistoryBean> list = new ArrayList<>();
        list.add(ph);

        //添加浏览记录
        int flag = playHistoryMapper.addPlayHistory(list);
        if (flag<0){
            js.put("code",401);
            js.put("msg","Fails");
        }else {
            js.put("code",200);
            js.put("msg","Success");
            //存储进es中
            playHistoryItemRepository.save(ph);
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String getPlayHistoryById(JSONObject json) {
        JSONObject js = new JSONObject();
        String objId = json.getString("obj_id");//对象编号。与用户ID二选一
        Integer userId = json.getInteger("user_id");//用户ID。与对象编号二选一
        Integer type = json.getInteger("obj_type");//内容类型：0商品 其他待定
        String content = json.getString("content");//搜索内容
        Integer page = json.getInteger("page");
        Integer size = json.getInteger("size");
        //初始页计算
        Integer starPage = (page - 1) * size;
        //若是objId不为空，则表示只需要查询总条数即可
        //否则需要查询完整的浏览信息
        if (null!=objId){
            //根据对象ID和类型查询该内容的浏览量
            Page<PlayHistoryBean> p = playHistoryItemRepository.findAllByObjIdAndPhTypeOrObjTitleIsLike(objId, type, content, PageRequest.of(starPage, size));
            js.put("playHistoryNum",p.getTotalPages());
            js.put("code",200);
            js.put("msg","Success");
        }else {
            //根据用户ID查询该用户的浏览记录
            Page<PlayHistoryBean> p = playHistoryItemRepository.findAllByUserIdOrObjTitleIsLike(userId, content, PageRequest.of(starPage, size));
            for (PlayHistoryBean play:p) {
                String objId1 = play.getObjId();
                Integer phType = play.getPhType();
                //根据对象内容ID和类型查询该内容的点赞量
                Page<UserCLRBean> like = userCLRItemRepository.findAllByObjIdAndClrType(phType, objId1, PageRequest.of(starPage, size));
                //根据对象内容ID和类型查询该内容的评论量
                Page<UserCommentBean> com = userCommentItemRepository.findAllByObjIdAndObjType(phType, objId1, PageRequest.of(starPage, size));
                play.setCommentNum(com.getTotalPages());
                play.setLikeNum(like.getTotalPages());
            }
        }
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updatePlayHistoryById(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o) {
            try {
                // 声明一个数组存储浏览记录ID
                List<Integer> oList = new ArrayList<>();
                // 前端传递参数
                JSONArray playList = json.getJSONArray("play_list");
                ObjectMapper o1 = new ObjectMapper();
                String s = o1.writeValueAsString(playList);
                List<PlayHistoryBean> list = o1.readValue(s, ArrayList.class);
                // 根据ID将用户ID列设置为空
                // 所谓的将浏览记录清空只是消除用户和该条浏览记录的联系
                // 但该内容的被浏览数据依旧要保留，已作统计功能
                for (PlayHistoryBean p:list) {
                    p.setUserId(null);
                    // 更新浏览记录
                    playHistoryItemRepository.save(p);
                    // 添加记录ID
                    oList.add(p.getPhId());
                }
                // 批量更新用户ID为空
                int flag = playHistoryMapper.updatePlayHistoryById(oList);
                if (flag<0){
                    js.put("code",401);
                    js.put("msg","Fails");
                }else {
                    js.put("code",200);
                    js.put("msg","Success");
                }
            }catch (Exception e){
                js.put("code",500);
                js.put("msg",e.getMessage());
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String deletePlayHistoryByIdAndType(JSONObject json) {
        JSONObject js = new JSONObject();
        String objId = json.getString("obj_id");//对象编码
        Integer type = json.getInteger("obj_type");//类型

        //删除浏览记录
        int flag = playHistoryMapper.deletePlayHistoryByIdAndType(objId,type);
        if (flag<0){
            js.put("code",401);
            js.put("msg","Fails");
        }else{
            js.put("code",200);
            js.put("msg","Success");

            //es删除
            playHistoryItemRepository.deleteByObjIdAndPhType(type,objId);
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }
}
